const Koa = require('koa');
const webpack = require('webpack'); // webpack模块
const router = require('koa-router')()
const KoaStatic = require('koa-static');

var convert = require('xml-js');
const fs = require('fs');

const app = new Koa();
var options = {
    key: fs.readFileSync('./cert/yang.key'),
    cert: fs.readFileSync('./cert/yang.pem')
};
const server = require('https').createServer(options,app.callback());
const io = require('socket.io')(server);
const config = require('../build/webpack.dev.conf'); // 开发环境模块
// const socketio = require('socket.io')




let compiler;
// 中间件容器，把webpack处理后的文件传递给一个服务器
const devMiddleware = require('./middleware/devMiddleware');
// 在内存中编译的插件，不写入磁盘来提高性能
// const hotMiddleware = require('./middleware/hotMiddleware');


//app.use(KoaStatic('../dist'));





router.get('/home', async (ctx, next) => {
	let rooms=io.sockets.adapter.rooms
	console.log("this is all rooms")
	console.log(rooms)
	console.log(rooms.length)


	// data = fs.readFileSync(__dirname + '/conf/vars.xml', 'utf8');
	// // console.log(data);

	// var result1 = convert.xml2json(data, {compact: false, spaces: 4});
	// var result2 = convert.json2xml(result1, {compact: false, spaces: 4});
	// fs.readFile(__dirname + '/vars.xml', function(err, data) {
	// 	var result1 = convert.xml2json(data, {compact: true, spaces: 4});
	// 	var result2 = convert.xml2json(data, {compact: false, spaces: 4});
	// });
// console.log(result1, '\n', result2);
		// ctx.response.body = result1+ '<br>'+ result2;
		ctx.response.body = rooms;
})

//根据传入路径修改xml文件信息。 注意 是post方法如http://127.0.0.1:3000/putxml?path=dialplan/default.xml&content=xml内容 
router.post("/putxml",async(ctx,next)=>{
	let path = ctx.query.path;
	let content=ctx.query.content;
	ctx.response.body=path+content;
})


//根据传入路径获取xml文件信息。如http://127.0.0.1:3000/getxml?path=dialplan/default.xml

router.get('/getxml', async (ctx, next) => {
	let ctx_query = ctx.query;
	path=ctx_query.path;
	data = fs.readFileSync(__dirname + '/conf/'+path, 'utf8');
	// console.log(123123)
	ctx.response.body=convert.xml2json(data, {compact: false, spaces: 4});
})









router.get('/404', async (ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'
})

 // 调用路由中间件
 app.use(router.routes())
//  socketio 和https进行绑定
// let server = require('http').createServer(app);
// let io = socketio(server);
// let io = socketio.listen(app)


 //socket.io的处理逻辑
io.on('connection',(socket)=>{
	socket.emit('message',{data:"你上线了",user:"管理员"});
	console.log('初始化成功！下面可以用socket绑定事件和触发事件了')
	socket.on('join',(room,username)=>{
		console.log("username is :"+ username)
		// socket.id=username
		socket.user=username
		socket.join(room)
		// 获取房间
		var userroom=io.sockets.adapter.rooms[room]
		// 获取房间人数
		var users = Object.keys(userroom.sockets).length
		//一个聊天室只能又2个人进行一对一通讯
		if(users<3){
			socket.emit('joined',room,socket.id);
			if(users >1){
				socket.to(room).emit('otherjoin',room)
			}
			console.log("room is:"+room+';number is :'+users)
		}else{
			console.log("room is:full leaveed")
			socket.emit('full',room,socket.id);
			socket.leave(room)
		}

		
		// socket.emit('joined',room,socket.id) //给本人回
		// socket.to(room).emit('joined',root,socket.id) //除自己之外的所有人
		// io.in(room).emit('joined',room,socket.id) //房间内所有人
		// socket.broadcast.emit('joined',room,socket.id) //除自己全部
	})


	socket.on('leave',(room)=>{		
		// 获取房间
		var userroom=io.sockets.adapter.rooms[room]
		// 获取房间人数
		var users =(userroom) ? Object.keys(userroom.sockets).length :0
		users=users-1
		console.log("room is:"+room+';number is :'+users)
		// socket.emit('joined',room,socket.id) //给本人回
		// socket.to(room).emit('joined',root,socket.id) //除自己之外的所有人
		// io.in(room).emit('joined',room,socket.id) //房间内所有人
		// socket.broadcast.emit('joined',room,socket.id) //除自己全部
		socket.to(room).emit('bye',room,socket.id)
		socket.emit("leaved",room,socket.id)
		socket.leave(room)
	})

	
	socket.on('message',(room,data)=>{
		// 获取客户端ip
		var socketId = socket.id
		var clientIp = socket.request.connection.remoteAddress
		console.log(socketId)
		console.log(clientIp)
		// 获取房间
		var userroom=io.sockets.adapter.rooms[room]
		// 获取房间人数
		try{
			var users = Object.keys(userroom.sockets).length
			console.log("room is:"+room+';number is :'+users+"data is:"+data)
			console.log(room)
		}
		catch(e){
			console.log('error..'+e)		
		}	
		// 发给所有人
		// io.in(room).emit('message',{data:data,user:socket.user})
		// 发给房间内除自己的所有人
		socket.emit('message',{data:data,user:socket.user,tpye:"echo"});
		socket.to(room).emit('message',{data:data,user:socket.user,type:"send"})
		

	})


})





config.then(function(s){
   compiler = webpack(s)
   app.use(devMiddleware(compiler))  
  server.listen(3000)
});
